<template>
  <div class="register-container">
    <el-form
      ref="registerFormRef"
      :model="registerForm"
      :rules="registerRules"
      class="register-form"
      autocomplete="on"
      label-position="left"
    >
      <div class="title-container">
        <h3 class="title">Easy Mall 后台管理系统</h3>
        <h4 class="subtitle">用户注册</h4>
      </div>

      <!-- 用户名 -->
      <el-form-item prop="username">
        <el-input
          ref="usernameRef"
          v-model="registerForm.username"
          placeholder="用户名"
          name="username"
          type="text"
          tabindex="1"
          autocomplete="on"
          prefix-icon="User"
        />
      </el-form-item>

      <!-- 密码 -->
      <el-form-item prop="password">
        <el-input
          ref="passwordRef"
          v-model="registerForm.password"
          :type="passwordVisible ? 'text' : 'password'"
          placeholder="密码"
          name="password"
          tabindex="2"
          autocomplete="on"
          prefix-icon="Lock"
        >
          <template #suffix>
            <el-icon class="cursor-pointer" @click="passwordVisible = !passwordVisible">
              <View v-if="passwordVisible" />
              <Hide v-else />
            </el-icon>
          </template>
        </el-input>
      </el-form-item>

      <!-- 确认密码 -->
      <el-form-item prop="confirmPassword">
        <el-input
          v-model="registerForm.confirmPassword"
          :type="confirmPasswordVisible ? 'text' : 'password'"
          placeholder="确认密码"
          name="confirmPassword"
          tabindex="3"
          autocomplete="on"
          prefix-icon="Lock"
        >
          <template #suffix>
            <el-icon class="cursor-pointer" @click="confirmPasswordVisible = !confirmPasswordVisible">
              <View v-if="confirmPasswordVisible" />
              <Hide v-else />
            </el-icon>
          </template>
        </el-input>
      </el-form-item>

      <!-- 验证码 -->
      <el-form-item prop="captcha">
        <div class="captcha-container">
          <el-input
            v-model="registerForm.captcha"
            placeholder="验证码"
            name="captcha"
            tabindex="4"
            autocomplete="off"
            prefix-icon="Key"
          />
          <div class="captcha-image" @click="refreshCaptcha">
            <img v-if="captchaImg" :src="captchaImg" alt="验证码" />
            <div v-else class="captcha-loading">加载中...</div>
          </div>
        </div>
      </el-form-item>

      <!-- 角色选择 -->
      <el-form-item prop="role">
        <el-select v-model="registerForm.role" placeholder="请选择角色" style="width: 100%">
          <el-option label="商家" value="ROLE_MERCHANT" />
          <el-option label="商家客服" value="ROLE_MERCHANT_SERVICE" />
          <el-option label="配送员" value="ROLE_DELIVERY" />
        </el-select>
      </el-form-item>

      <!-- 注册按钮 -->
      <el-button
        :loading="loading"
        type="primary"
        class="register-button"
        @click="handleRegister"
      >
        注册
      </el-button>

      <!-- 返回登录 -->
      <div class="login-link">
        <router-link to="/login">已有账号？返回登录</router-link>
      </div>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '../../store/user'

// 路由
const router = useRouter()

// 用户store
const userStore = useUserStore()

// 表单引用
const registerFormRef = ref()
const usernameRef = ref()
const passwordRef = ref()

// 密码可见性
const passwordVisible = ref(false)
const confirmPasswordVisible = ref(false)

// 加载状态
const loading = ref(false)

// 验证码图片
const captchaImg = ref('')
const captchaKey = ref('')

// 注册表单
const registerForm = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  captcha: '',
  role: 'ROLE_MERCHANT'
})

// 表单验证规则
const validatePass = (rule: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    if (registerForm.confirmPassword !== '') {
      registerFormRef.value.validateField('confirmPassword')
    }
    callback()
  }
}

const validatePass2 = (rule: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== registerForm.password) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, validator: validatePass, trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, validator: validatePass2, trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 4, max: 6, message: '验证码长度不正确', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}

// 刷新验证码
const refreshCaptcha = async () => {
  try {
    const res = await userStore.getCaptcha()
    captchaImg.value = res.captchaImage
    captchaKey.value = res.captchaKey
  } catch (error) {
    console.error('获取验证码失败:', error)
    ElMessage.error('获取验证码失败，请刷新页面重试')
  }
}

// 处理注册
const handleRegister = () => {
  registerFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true
      try {
        await userStore.register({
          username: registerForm.username,
          password: registerForm.password,
          captcha: registerForm.captcha,
          captchaKey: captchaKey.value,
          role: registerForm.role
        })
        
        ElMessage.success('注册成功，请登录')
        router.push('/login')
      } catch (error: any) {
        ElMessage.error(error.message || '注册失败，请重试')
        // 刷新验证码
        refreshCaptcha()
      } finally {
        loading.value = false
      }
    } else {
      return false
    }
  })
}

// 组件挂载时获取验证码
onMounted(() => {
  refreshCaptcha()
})
</script>

<style lang="scss" scoped>
.register-container {
  min-height: 100vh;
  width: 100%;
  background-color: #2d3a4b;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
  
  .register-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    padding: 160px 35px 0;
    margin: 0 auto;
    overflow: hidden;
    
    .register-button {
      width: 100%;
      margin-bottom: 30px;
    }
    
    .login-link {
      text-align: center;
      font-size: 14px;
      margin-bottom: 20px;
      
      a {
        color: #fff;
        text-decoration: none;
        
        &:hover {
          text-decoration: underline;
        }
      }
    }
  }
  
  .title-container {
    position: relative;
    
    .title {
      font-size: 26px;
      color: #eee;
      margin: 0 auto 10px auto;
      text-align: center;
      font-weight: bold;
    }
    
    .subtitle {
      font-size: 18px;
      color: #eee;
      margin: 0 auto 40px auto;
      text-align: center;
      font-weight: normal;
    }
  }
  
  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }
  
  .captcha-container {
    display: flex;
    width: 100%;
    
    .el-input {
      flex: 1;
    }
    
    .captcha-image {
      width: 120px;
      height: 40px;
      margin-left: 10px;
      background-color: #fff;
      border-radius: 4px;
      cursor: pointer;
      display: flex;
      justify-content: center;
      align-items: center;
      overflow: hidden;
      
      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
      
      .captcha-loading {
        color: #606266;
        font-size: 12px;
      }
    }
  }
  
  .el-input {
    display: inline-block;
    height: 40px;
    width: 100%;
    
    :deep(.el-input__wrapper) {
      background-color: transparent;
      box-shadow: none;
      padding: 0;
    }
    
    :deep(.el-input__inner) {
      background-color: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      color: #fff;
      height: 40px;
      
      &:-webkit-autofill {
        box-shadow: 0 0 0 1000px #283443 inset !important;
        -webkit-text-fill-color: #fff !important;
      }
    }
  }
  
  .el-select {
    :deep(.el-input__wrapper) {
      background-color: transparent;
      box-shadow: none;
    }
    
    :deep(.el-input__inner) {
      color: #fff;
    }
    
    :deep(.el-select__icon) {
      color: #fff;
    }
  }
}
</style>